package com.atguigu.tingshu.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.account.client.RechargeInfoFeignClient;
import com.atguigu.tingshu.account.client.UserAccountFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.order.client.OrderInfoFeignClient;
import com.atguigu.tingshu.payment.config.WxPayV3Config;
import com.atguigu.tingshu.payment.mapper.PaymentInfoMapper;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.core.exception.ServiceException;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.QueryOrderByOutTradeNoRequest;
import com.wechat.pay.java.service.payments.model.Transaction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

import static com.baomidou.mybatisplus.extension.toolkit.Db.getOne;

@Service
@Slf4j
@SuppressWarnings({"unchecked", "rawtypes"})
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    @Autowired
    private OrderInfoFeignClient orderInfoFeignClient;

    @Autowired
    private RechargeInfoFeignClient rechargeInfoFeignClient;

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private WxPayV3Config wxPayV3Config;

    @Override
    public PaymentInfo savePaymentInfo(String paymentType, String orderNo, Long userId) {
        //  获取到交易记录对象
        PaymentInfo paymentInfo = this.getOne(new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo, orderNo));
        if (null == paymentInfo) {
            //  创建对象
            paymentInfo = new PaymentInfo();
            //  支付信息
            if (paymentType.equals(SystemConstant.PAYMENT_TYPE_ORDER)) {
                //  远程调用获取到订单对象
                Result<OrderInfo> orderInfoResult = orderInfoFeignClient.getOrderInfoByOrderNo(orderNo, userId);
                Assert.notNull(orderInfoResult, "返回订单对象不能为空");
                OrderInfo orderInfo = orderInfoResult.getData();
                Assert.notNull(orderInfo, "返回订单对象不能为空");
                paymentInfo.setUserId(orderInfo.getUserId());
                paymentInfo.setContent(orderInfo.getOrderTitle());
                paymentInfo.setAmount(orderInfo.getOrderAmount());
            } else {
                //  充值信息
                Result<RechargeInfo> rechargeInfoResult = rechargeInfoFeignClient.getRechargeInfo(orderNo);
                Assert.notNull(rechargeInfoResult, "返回充值对象不能不为空");
                RechargeInfo rechargeInfo = rechargeInfoResult.getData();
                Assert.notNull(rechargeInfo, "返回充值对象不能不为空");
                paymentInfo.setUserId(rechargeInfo.getUserId());
                paymentInfo.setContent("充值");
                paymentInfo.setAmount(rechargeInfo.getRechargeAmount());
                // 给用户增加余额
            }
            paymentInfo.setPaymentType(paymentType);
            paymentInfo.setOrderNo(orderNo);
            paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_UNPAID);
            this.save(paymentInfo);
        }
        return paymentInfo;
    }

    @Override
    public void updatePaymentStatus(Transaction transaction) {
        String outTradeNo = transaction.getOutTradeNo();
        PaymentInfo paymentInfo = getOne(new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo,outTradeNo));
        if (Objects.equals(paymentInfo.getPaymentStatus(), SystemConstant.PAYMENT_STATUS_PAID)) {
            return;
        }
        //更新支付信息
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_PAID);
        paymentInfo.setOrderNo(outTradeNo);
        paymentInfo.setOutTradeNo(transaction.getTransactionId());
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(JSON.toJSONString(transaction));
        updateById(paymentInfo);

        String routing = paymentInfo.getPaymentType().equals(SystemConstant.PAYMENT_TYPE_ORDER) ? MqConst.ROUTING_ORDER_PAY_SUCCESS : MqConst.ROUTING_RECHARGE_PAY_SUCCESS;
        // 如果是买商品 就发信息给订单服务(paySuccess 和零钱支付一样的逻辑) 充值就发信息给充值服务
        rabbitService.sendMessage(MqConst.EXCHANGE_ORDER, routing, paymentInfo.getOrderNo());
    }

    @Override
    public Transaction queryOrderByOutTradeNo(QueryOrderByOutTradeNoRequest queryRequest, String orderNo) {
        queryRequest.setMchid(wxPayV3Config.getMerchantId());
        queryRequest.setOutTradeNo(orderNo);
        try {
            JsapiServiceExtension service = new JsapiServiceExtension.Builder().config(wxPayV3Config.getConfig()).signType("RSA") // 不填默认为RSA
                    .build();
            Transaction result = service.queryOrderByOutTradeNo(queryRequest);
            log.info(JSON.toJSONString(result));
            return result;
        } catch (ServiceException e) {
            // API返回失败, 例如ORDER_NOT_EXISTS
            System.out.printf("code=[%s], message=[%s]\n", e.getErrorCode(), e.getErrorMessage());
            System.out.printf("reponse body=[%s]\n", e.getResponseBody());
        }

        return null;
    }


}
